{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 多线程\n",
    "- 优点：程序同时运行多个线程，增加硬件和cpu的利用率\n",
    "- t1=threading.Thread(target=‘一个线程’,args=（参数）) ：实例化一个线程，target指向一个函数，args使用元祖储存变量\n",
    "- t.start():开始一个线程\n",
    "- t.join():直到该线程结束后才执行下一条语句\n",
    "- `__name__ `== \"`__main__`\" : 只有当该文件主文件的时候才为真"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "process start->>> Wed Sep 26 21:42:21 2018\nfunc1 start->>>>>: Wed Sep 26 21:42:21 2018\nfunc2 start->>>>> Wed Sep 26 21:42:21 2018\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "func1 end->>>>> Wed Sep 26 21:42:23 2018\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "func2 end->>>>> Wed Sep 26 21:42:25 2018\nprocess end ->>>> Wed Sep 26 21:42:25 2018\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "import threading\n",
    "def func1(*args):\n",
    "    print('func1 start->>>>>:',time.ctime())\n",
    "    time.sleep(2)\n",
    "    print('func1 end->>>>>',time.ctime())\n",
    "def func2(*args):\n",
    "    print('func2 start->>>>>',time.ctime())\n",
    "    time.sleep(4)\n",
    "    print('func2 end->>>>>',time.ctime())\n",
    "def main():\n",
    "    print('process start->>>',time.ctime())\n",
    "    # 生成一个线程实例\n",
    "    t1 = threading.Thread(target=func1,args=('lsl',))   # 函数和参数\n",
    "    # 开始一个线程\n",
    "    t1.start()\n",
    "    t2 = threading.Thread(target=func2,args=('lsl',))\n",
    "    t2.start()\n",
    "    #  线程join\n",
    "    t1.join()\n",
    "    t2.join()\n",
    "    print('process end ->>>>',time.ctime())\n",
    "if __name__==\"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 守护线程（daemon）\n",
    "- 定义：随着主线程结束而结束\n",
    "- 设置为守护进程：t.setDaemon(True) 或者 t.daemon=True\n",
    "- 非守护进程：主线程和其他线程分别执行，互不影响"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "process start\nfun start\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "process end\n"
     ]
    }
   ],
   "source": [
    "# 非守护进程例子，可能由于jupyter的原因不能正确显示结果\n",
    "import time\n",
    "import threading\n",
    "def fun():\n",
    "    print('fun start')\n",
    "    time.sleep(4)\n",
    "    print('fun end')\n",
    "print('process start')\n",
    "t = threading.Thread(target=fun,args=())\n",
    "t.setDaemon(True)   #设置守护线程\n",
    "t.start()\n",
    "time.sleep(2)\n",
    "print('process end')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# threading 常见属性\n",
    "- threading.currentThread():当前线程\n",
    "- threading.enumerate():以元祖的方式返回所有的线程名\n",
    "- threading.activeCount():正在运行的元祖个数\n",
    "- t1.setName():给线程设置名字\n",
    "- t2.getName():获取线程的名字"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 共享变量\n",
    "- 定义： 两个或者多个同时使用的变量，如果同时访问，会出现错误\n",
    "- 解决：锁（lcok） 一个线程使用的时候其他线程排队\n",
    "- 操作步骤：lock=threading.lock() ->lock.acquire()->代码-》lock.release()\n",
    "- 线程不安全的变量类型：list,dict,set\n",
    "- 线程安全：队列（queue）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start sum is 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "end sum is 199425355378\n"
     ]
    }
   ],
   "source": [
    "# 出现了线程共享变量的问题\n",
    "import threading\n",
    "sum = 0 \n",
    "num = 1000000\n",
    "def add():\n",
    "    global sum,num\n",
    "    for i in range(0,num):\n",
    "        sum += i\n",
    "def miue():\n",
    "    global sum,num\n",
    "    for i in range(0,num):\n",
    "        sum -= i\n",
    "print('start sum is {}'.format(sum))\n",
    "t1 = threading.Thread(target=add,args=())\n",
    "t2 = threading.Thread(target=miue,args=())\n",
    "t1.start()\n",
    "t2.start()\n",
    "t1.join()\n",
    "t2.join()\n",
    "print('end sum is {}'.format(sum))\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "start sum is 0\nend sum is 0\n"
     ]
    }
   ],
   "source": [
    "# 加个锁,就不会出错了\n",
    "import threading\n",
    "sum = 0 \n",
    "num = 10000\n",
    "mylock = threading.Lock()\n",
    "def add():\n",
    "    global sum,num\n",
    "    for i in range(0,num):\n",
    "        mylock.acquire()\n",
    "        sum += i\n",
    "        mylock.release()\n",
    "def miue():\n",
    "    global sum,num\n",
    "    for i in range(0,num):\n",
    "        mylock.acquire()\n",
    "        sum -= i\n",
    "        mylock.release()\n",
    "print('start sum is {}'.format(sum))\n",
    "t1 = threading.Thread(target=add,args=())\n",
    "t2 = threading.Thread(target=miue,args=())\n",
    "t1.start()\n",
    "t2.start()\n",
    "t1.join()\n",
    "t2.join()\n",
    "print('end sum is {}'.format(sum)) "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
